using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
using TaskScheduling.Middleware;
using TS.Common.Db;
using TS.Services;

var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
    ContentRootPath = AppDomain.CurrentDomain.BaseDirectory,
    ApplicationName = typeof(Program).Assembly.FullName,
    Args = args,
});


#region SerialLog

var logfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log", "log.txt");

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
#if DEBUG
    .WriteTo.Console(LogEventLevel.Information, theme: AnsiConsoleTheme.Literate)
#endif
    // .WriteTo.File(logfile, LogEventLevel.Information, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 90, outputTemplate: "{NewLine}Date：{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel：{Level}{NewLine}Message：{Message}{NewLine}{Exception}")
    .WriteTo.Async(
        configure =>
        {
            configure.File(logfile, LogEventLevel.Information, rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 90,
                outputTemplate:
                "{NewLine}Date：{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel：{Level}{NewLine}Message：{Message}{NewLine}{Exception}");
        }, 1000)
    .CreateLogger();

#endregion

#region WindowsUseService

bool isService =
    !(Debugger.IsAttached || args.Contains("--console")); //Debug状态或者程序参数中带有--console都表示普通运行方式而不是Windows服务运行方式
if (isService)
{
    //平台是windows的时候
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
        builder.Host.UseWindowsService();
    }
}

#endregion


var port = builder.Configuration.GetValue<int>("Port");
if (port == 0) port = 5000;
builder.WebHost.UseKestrel(web =>
    web.ListenAnyIP(port)
);
///注入
builder.Host.ConfigureContainer<ContainerBuilder>(builder => { builder.AutofaceDI(); });
builder.Services.AddHttpClient();

builder.Services.Configure<MvcOptions>(opts =>
{
    //filter 配置
    opts.Filters.Add<ApiAuthorizeAttribute>();
    opts.Filters.Add<GlobalExceptionCatchFilter>();
});

builder.Services.Configure<JsonOptions>(opts =>
{
    opts.JsonSerializerOptions.PropertyNamingPolicy = null; //解决后端传到前端全大写
    opts.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); //解决后端返回数据中文被编码
});
//添加日志服务
builder.Services.AddLogging();

//controller注册成服务
builder.Services.AddControllersWithViews().AddControllersAsServices();
// 设置允许所有来源跨域
builder.Services.AddCors(options => options.AddPolicy("CorsPolicy",
    builder =>
    {
        builder.WithOrigins("urls")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .SetIsOriginAllowed(_ => true) // =AllowAnyOrigin()
            .AllowCredentials();
    }));

builder.Host
    .UseSerilog(Log.Logger)
    .UseServiceProviderFactory(new AutofacServiceProviderFactory());


try
{
    var app = builder.Build();
    
    // 使用跨域配置
    app.UseCors("CorsPolicy");
    //文件服务
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(app.Environment.WebRootPath),
        ServeUnknownFileTypes = true,
    });
    //路由
    app.UseRouting();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    app.MapFallbackToFile("index.html");
    //初始化表 
    InitTable.InitTableAndData();
    //初始化任务
    app.Services.GetService<TaskService>()!.InitJob().GetAwaiter().GetResult();
    app.Run();
}
catch (Exception e)
{    
    Log.Error(e, "服务停止");
}